<?php

namespace App\Http\Controllers\Api;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\AddShortUrlResponseBody\data;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use AlipayTradeWapPayContentBuilder;
use AlipayTradeService;
use AopClient;
use AlipayTradeAppPayRequest;


class Pay extends Controller
{
    //H5支付
    public function payH5(Request $request)
    {

        $config = [
            //应用ID,您的APPID。
            'app_id' => env('APP_ID'),
            //商户私钥，您的原始格式RSA私钥
            'merchant_private_key' => env('MERCHANT_PRIVATE_KEY'),
            //异步通知地址
            'notify_url' => env('NOTIFY_URL'),
            //同步跳转
            'return_url' => env('RETURN_URL'),
            //编码格式
            'charset' => 'UTF-8',
            //签名方式
            'sign_type' => 'RSA2',
            //支付宝网关
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => env('ALI_PUB_KEY'),
            //日志路径
            'log_path' => "",
        ];

        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = "SW".date("YMDHis").mt_rand(10000,99999);

        //订单名称，必填
        $subject = "wanneiyao";

        //付款金额，必填
        $total_amount = "0.01";

        //商品描述，可空
        $body = "";

        //超时时间
        $timeout_express="30m";
        $payRequestBuilder = new AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);

        $payResponse = new AlipayTradeService($config);
        $result=$payResponse->wapPay($payRequestBuilder,$config['return_url'],$config['notify_url']);
        return response()->json(['status'=>200,"msg"=>"请求成功",'data'=>$result]);
    }

    //App 支付
    public function payApp(Request $request){
        $aop = new AopClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = env('APP_ID');
        $aop->rsaPrivateKey = env('MERCHANT_PRIVATE_KEY');
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = env('ALI_PUB_KEY');
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        $bizcontent = "{\"body\":\"我是测试数据\","
            . "\"subject\": \"App支付测试\","
            . "\"out_trade_no\": \"20170125test0101\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"0.01\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $request->setNotifyUrl(env('NOTIFY_URL'));
        $request->setBizContent($bizcontent);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        echo htmlspecialchars($response);//就是orderString 可以直接给客户端请求，无需再做处理。
    }


    public function payWx()
    {
        $time = time()+8*60*60;
        $params = array(
            'appid' => env('WX_APP_ID'),
            'mch_id' => env('WX_APP_MCH_ID'),
            'nonce_str' => '1954518657',
            'body' => "眠素双拼60s简绣四件套x1",
            'out_trade_no' => "SW".date("YmdHis").mt_rand(10000,99999),//'1090220928030756427696',
            'attach' => 'attach',
            'total_fee' => '7918',
            'spbill_create_ip' => '182.118.232.40',//$_SERVER['REMOTE_ADDR'],
            'notify_url' => "http://payapi.9617777.com/pay/wxpay/callback",//env('WX_APP_NOTIFY_URL'),
            "time_start" => date("YmdHis",$time),
            "time_expire" => date("YmdHis",$time+30*60),
            "sign_type" => "MD5",
            'trade_type' => env('WX_APP_TRADE_TYPE'),
            "key"=>env("WX_APP_SECRET"),
            "gateUrl"=>env("WX_APP_GATEURL"),
            "service"=>env("WX_APP_SERVICERAW")
        );

        $service = $params['service'];unset($params['service']);
        $gateUrl = $params['gateUrl'];unset($params['gateUrl']);
        $key = $params['key'];unset($params['key']);
        $params['sign'] = generateSign($params);

        $url = $gateUrl.$service;
        $xml = $this->arrayToXml($params);
        $response = $this->sendRequest($url, $xml);

        $result = $this->xmlToArray($response);

        $res = [];
        if($result['return_code']=='SUCCESS'){
            $res['appid'] = $result['appid'];
            $res['partnerid'] = strval($result['mch_id']);
            $res['prepayid'] = strval($result['prepay_id']);
            $res['package'] = "Sign=WXPay";
            $res['noncestr'] = strval(mt_rand(time(),time()+rand()));
            $res['timestamp'] = strval(time());
            $res['sign'] = generateSign($res);
            return response()->json(['status'=>200,'msg'=>"下单成功",'data'=>$res]);
        }else{
            return response()->json(['status'=>202,'msg'=>"下单失败",'data'=>[]]);
        }
    }

    public  function arrayToXml($array) {
        $xml = "<xml>";
        foreach ($array as $key => $value) {
            $xml .= "<{$key}><![CDATA[{$value}]]></{$key}>";
        }
        $xml .= "</xml>";

        return $xml;
    }

    public function xmlToArray($xml)
    {
        // 先用simplexml_load_string函数转换xml字符串为对象，再把对象转换为JSON字符串，最后再转换JSON字符串为数组        // LIBXML_NOCDATA - 将 CDATA 设置为文本节点
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    public function sendRequest($url, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT,env('WX_APP_CERTPATH'));
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, env('WX_APP_KEYPATH'));
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
}
